import Vue from 'vue'
import Router from 'vue-router'
import Login from '../views/login/login'
import Layout from '../views/Layout/layout'
import Home from '../views/Home/home'

Vue.use(Router)

const router = new Router({
  // mode: 'history',
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: Login
    },
    {
      path: '/',
      name: 'Layout',
      component: Layout,
      meta: {
        requiresAuth: true
      }
      // children: {
      //   path: '/home',
      //   component: Home,
      //   meta: {
      //     requiresAuth: true
      //   }
      // }
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  let USER_TOKEN = window.sessionStorage.getItem('user_token')
  // console.log('进入路由守卫！')
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // console.log('进入守卫验证！')
    if (USER_TOKEN !== 'admin') {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    // console.log('通过守卫进入 from 路由！')
    next() // 确保一定要调用 next()
  }
})

export default router
